//
//  MYXpublishDealViewController.m
//  meiyinxiang
//
//  Created by 陈李飞 on 2017/11/29.
//  Copyright © 2017年 hbjApple. All rights reserved.
//我的发布详情

#import "MYXpublishDealViewController.h"
#import "MYXRecommendDetailController.h"
//cell
#import "LukyMoneyDetailContentCell.h"
#import "GetLuckyMoneyListCell.h"
#import "RecievedLukcyDetailTableViewCell.h"
#import "MYXpublishDealTopCell.h"
#import "MYXRecieveMoneyListViewModel.h"

static NSString *const MYXpublishDealTopCellCellIdentifier = @"MYXpublishDealTopCell";
@interface MYXpublishDealViewController ()
<UITableViewDelegate,
UITableViewDataSource>
{
    CGFloat lastOriginalY;
    LukyMoneyDetailContentCell *contenCell ;
    RecievedLukcyDetailTableViewCell *recievedDetailCell;
    MYXpublishDealTopCell *MYXpublishDealTopCe;
    UITextField *leaveMessageTextField;
    
}
@property (nonatomic,strong) UITableView *tableView;
@end

@implementation MYXpublishDealViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTime) name:Post5SecondSucessNotificationName object:nil];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
    [self.detailviewModel hidekeybord];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:Post5SecondSucessNotificationName object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configTableView];
  //  [self addTableViewHeigt];
    [self addrefresh];
    AdjustsScrollViewInsetNever(self, self.tableView);
}
- (void)addrefresh{
    WS(weakSelf);
    //上拉加载更多
    //    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer  =   [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf.detailviewModel getMoneyDetailWithIsPullup:YES Completion:^(BOOL success, NSString *message) {
            if (success) {
                [weakSelf.tableView reloadData];
                [weakSelf.tableView.mj_footer endRefreshing];
            }else{
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }];
    }];
}
- (void)refreshTime{
    NSLog(@"5 second is comming");
    WS(weakSelf);
    [self.model getMoneyDetailWithIsPullup:NO Completion:^(BOOL success, NSString *message) {
        if (success) {
            weakSelf.detailviewModel = weakSelf.model.viewModel;
            [weakSelf.tableView reloadData];
        }
        weakSelf.detailviewModel.isSecondRefresh = YES;
    }];
    
}
- (void)addTableViewHeigt{
    __weak typeof(self) weakself = self;
    if (self.loadImgView == nil) {
        self.loadImgView = [[UIImageView alloc] init];
    }
   // self.loadImgView.contentMode = UIViewContentModeScaleAspectFill
    [self.loadImgView sd_setImageWithURL:[NSURL URLWithString:_detailviewModel.file] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        //没有照片
        if (!image) {
            weakself.detailviewModel.cellHeight = weakself.detailviewModel.cellHeight - 110;
            return ;
        }
        //计算图片大小
        CGFloat  widthCons = 175;
        CGFloat  heightCons = 110;
        CGFloat imageHeight = image.size.height;
        CGFloat imageWidth = image.size.width;
        
        if (imageWidth <  imageHeight) {
            heightCons = widthCons/(imageWidth/imageHeight);
            
        }else{
            widthCons = ScreenWidth - 20;
            heightCons = widthCons/(imageWidth/imageHeight);
            
        }
        
        if (heightCons != 110) {
            //更新cell高度
            weakself.detailviewModel.cellHeight = weakself.detailviewModel.cellHeight - 110 + heightCons;
            NSIndexSet *set = [NSIndexSet indexSetWithIndex:0];
            
            [weakself.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationNone];
        }
        
        
    }];
}
#pragma mark -PrivateMethod

- (void)configTableView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(0);
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.bottom.equalTo(@0);
    }];
     [self.tableView registerNib:[UINib nibWithNibName:MYXpublishDealTopCellCellIdentifier bundle:nil] forCellReuseIdentifier:MYXpublishDealTopCellCellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:@"LukyMoneyDetailContentCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:LukyMoneyDetailContentCellReuseId];
    [self.tableView registerNib:[UINib nibWithNibName:@"GetLuckyMoneyListCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:GetLuckyMoneyListCellResuId];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"RecievedLukcyDetailTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:RecievedLukcyDetailReuseId];
    
}
#pragma mark -UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0||section == 1) {
        return 1;
    }else if (section == 2){
        return self.detailviewModel.marray.count > 0 ? _detailviewModel.marray.count : _detailviewModel.list.count;
    }
    return 0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        contenCell = [tableView dequeueReusableCellWithIdentifier:LukyMoneyDetailContentCellReuseId forIndexPath:indexPath];
        if (contenCell == nil) {
            contenCell = [LukyMoneyDetailContentCell loadNibWithLukyMoneyDetailContentCell];
        }
        contenCell.mSuperVC = self;
        [contenCell.backBtn addTarget:self action:@selector(backAct) forControlEvents:UIControlEventTouchUpInside];
        self.detailviewModel.isController = @"1";
        contenCell.detailModel = self.detailviewModel;
        WS(weakSelf);
        contenCell.detailModel.singleImgFinishBlock= ^(BOOL isdone){
            if (isdone) {
                NSIndexSet *set = [NSIndexSet indexSetWithIndex:0];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];
                });
            }
        };
        return contenCell;
        
    }else if (indexPath.section == 1){
        MYXpublishDealTopCe = [tableView dequeueReusableCellWithIdentifier:MYXpublishDealTopCellCellIdentifier forIndexPath:indexPath];
        MYXpublishDealTopCe.selectionStyle = UITableViewCellSelectionStyleNone;
        MYXpublishDealTopCe.titileLabel.text = [NSString stringWithFormat:@"已领取%@/%@",self.detailviewModel.restcount,self.detailviewModel.rcount];
        
        return MYXpublishDealTopCe;
    }
    else{
        GetLuckyMoneyListCell *listCell = [tableView dequeueReusableCellWithIdentifier:GetLuckyMoneyListCellResuId forIndexPath:indexPath];
        if (listCell == nil) {
            listCell = [GetLuckyMoneyListCell loadNibWithListCell];
        }
        MYXRecieveMoneyListViewModel *detailModel =  [self.detailviewModel.marray objectAtIndex:indexPath.row] ;
        listCell.detailModel = detailModel;
        return listCell;
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return self.detailviewModel.cellHeight;
    }else if (indexPath.section == 2){
        MYXRecieveMoneyListViewModel *listViewModel = self.detailviewModel.marray[indexPath.row];
        return listViewModel.cellHeight;
    }
    else{
        return 30;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
   
    UIView *fooerView =[[UIView alloc]init];
    if (section==0) {
        fooerView.frame =CGRectMake(0, 0, WIDTH, 10);
    }else{
       fooerView.frame =CGRectMake(0, 0, WIDTH, 0.1);
    }
    fooerView.backgroundColor =MYYColorFromRGB(0xf2f2f2);
    return fooerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
      if (section==0) {
          return 10;
      }
    return 0.1;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 0.1)];
    headView.backgroundColor =MYYlineColor;
    
    return headView;
}
-(CGFloat )tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
  //  NSLog(@"scrollview offset %f",scrollView.contentOffset.y);
    lastOriginalY = scrollView.contentOffset.y;
    CGFloat consTop;
    CGFloat height;
    if (lastOriginalY < 0) {
        consTop  = - lastOriginalY;
        height =  - lastOriginalY + 110;
    }else{
        consTop = 0;
        height = 110;
    }
    if (contenCell) {
        contenCell.topCons.constant = -consTop;
        contenCell.bgheightCons.constant = height;
    }
    if (recievedDetailCell) {
        recievedDetailCell.topCons.constant = -consTop;
        recievedDetailCell.bgheightCons.constant = height;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.detailviewModel hidekeybord];
    UITableViewCell *selectCell = [tableView cellForRowAtIndexPath:indexPath];
    MYXRecieveMoneyListViewModel *detailModel = [self.detailviewModel.marray objectAtIndex:indexPath.row] ;
    if ([selectCell isKindOfClass:[GetLuckyMoneyListCell class]] && detailModel.content.length > 0) {
        MYXRecommendDetailController *recommendDetailVC = [[MYXRecommendDetailController alloc] init];
        recommendDetailVC.redPacketId = detailModel.cateLuckyMoneyId;
        recommendDetailVC.commentManId = detailModel.tid;
        [self.navigationController pushViewController:recommendDetailVC animated:YES];
    }
   // recievedDetailCell.leaveMessageBtn.userInteractionEnabled = YES;
}
#pragma mark -PrivateMethod
- (void)backAct{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"info" object:nil];
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)leavemessage:(UIButton *)sender{
    __weak typeof(self) weakself = self;
    NSIndexSet *set = [NSIndexSet indexSetWithIndex:1];
    [self.detailviewModel showCommentTextWithFinshBlock:^(BOOL isSucess) {
        if (isSucess) {
            [weakself.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];            recievedDetailCell.leaveMessageBtn.enabled = NO;
        }
    }];
    //这里是为了防止连续点击
    sender.userInteractionEnabled = NO;
    [sender performSelector:@selector(setUserInteractionEnabled:) withObject:@YES afterDelay:1];
    // [self showCommentText];
}
- (void)returncontent {
    self.detailviewModel.isreceived = @"0";
    NSIndexSet *set = [NSIndexSet indexSetWithIndex:0];
    [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
